import random
from string import digits, ascii_letters
from PIL import Image, ImageDraw, ImageFont, ImageFilter
from io import BytesIO
from typing import List

# 验证码字体文件路径
FONT_PATH = "path/to/your/font.ttf"


def generate_captcha_text(length: int = 4) -> str:
	characters = digits + ascii_letters
	return ''.join(random.choices(characters, k=length))


def create_captcha_image(text: str) -> bytes:
	width, height = 120, 40
	image = Image.new("RGB", (width, height), color=(255, 255, 255))
	draw = ImageDraw.Draw(image)

	# 设置字体并绘制文本
	font = ImageFont.truetype(FONT_PATH, 30)
	text_width, _ = draw.textsize(text, font=font)
	x = (width - text_width) // 2
	y = (height - font.getsize(text)[1]) // 2
	draw.text((x, y), text=text, fill=(0, 0, 0), font=font)

	# 添加一些噪点以增加识别难度（可选）
	for _ in range(100):
		draw.point((random.randint(0, width), random.randint(0, height)),
		           fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))

	# 将图像转换为JPEG格式并输出到BytesIO对象中
	buffer = BytesIO()
	image = image.filter(ImageFilter.BLUR)  # 可选：模糊处理
	image.save(buffer, format="JPEG")
	buffer.seek(0)

	return buffer.getvalue()


def verify_captcha(captcha_text: str, expected_text: str) -> bool:
	return captcha_text.lower() == expected_text.lower()


# 示例用法
captcha_code = generate_captcha_text()
image_data = create_captcha_image(captcha_code)
# 在FastAPI应用中使用image_data作为响应内容